#pragma once
#include <iostream>
#include <string>
#include <pthread.h>
#include <functional>
#include <vector>
#include <unistd.h>
//封装一下线程库

//线程库：线程创建、线程终止、线程等待、线程分离
//pthread_create pthread_cancel pthread_exit pthread_join pthread_detach  pthread_setname_np->用来给

//线程通过回调函数执行相关的方法
//未进行同步互斥保护
namespace wnf
{
    //用来辅助线程命名
    using func = std::function<void()>;//回调函数，执行一些功能
    class Thread
    {
        private:
        static pthread_mutex_t mutex1;
        static pthread_mutex_t mutex2;
        static int number;
        //相关的辅助函数,只在内部使用

        static void* start_routine(void* arg)
        {
            Thread* ptr = static_cast<Thread*>(arg);
            pthread_setname_np(ptr->_thread,ptr->_name.c_str());
            return ptr->Func();
        }
        public:
            //传入相关回调方法
            Thread(const func& f):_thread(0),_running_flag(0),_func(f),_detach_flag(0),_stop_flag(0)
            {
                pthread_mutex_lock(&mutex1);
                _name = "thread_" + std::to_string(number++);
                pthread_mutex_unlock(&mutex1);
            }
        
            bool Create()
            {
                if(_running_flag)
                    return false;
                _running_flag = 1;
                int ret = pthread_create(&_thread,nullptr,start_routine,(void*)this);
                return !ret;
            }

            void* Func()
            {
                char buffer[100] = {0};
                pthread_getname_np(_thread,buffer,sizeof(buffer) - 1);
                pthread_mutex_lock(&mutex2);
                std::cout << buffer << "完成任务:";
                this->_func();
                pthread_mutex_unlock(&mutex2);
                return (void*)0;
            }

            //要尽量避免使用pthread_cancel，这个调用的最终导致的行为太过不稳定，对于多线程而言，并不安全
            //可以使用一个停止标志位
            bool Stop()
            {
                if(!_running_flag)
                    return false;
                int ret = pthread_cancel(_thread);
                return !ret;
            }

            bool Join()
            {
                if(!_running_flag || _detach_flag)
                    return false;
                int ret = pthread_join(_thread,nullptr);
                pthread_mutex_lock(&mutex2);

                if(!ret)
                    std::cout << _name << "回收成功" << std::endl;
                pthread_mutex_unlock(&mutex2);

                return !ret;
            }

            bool Detach()
            {
                if(!_running_flag)
                    return false;
                int ret = pthread_detach(_thread);
                if(!ret)
                    _detach_flag = 1;
                return !ret;
            }
        private:
            pthread_t _thread;//线程id
            std::string _name;//线程名
            bool _running_flag;//运行状态
            bool _detach_flag;//分离状态
            bool _stop_flag;//停止标志位
            func _func;//回调方法
    };
}
